package org.wevil.controller.sys;

import org.wevil.entity.sys.SysMenu;
import org.wevil.enumu.ResultEnum;
import org.wevil.params.add.MenuAP;
import org.wevil.params.update.MenuUP;
import org.wevil.service.sys.MenuService;
import org.wevil.util.BeanUtil;
import org.wevil.util.JwtUtil;
import org.wevil.util.NodeUtil;
import org.wevil.vo.Result;
import org.wevil.vo.list.MenuListVo;
import org.wevil.vo.node.MenuNodeVo;
import org.wevil.vo.node.NodeVo;



import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Validated
/** 菜单管理 */
@RestController
@RequestMapping("/sys/menu")
public class MenuController {

    @Resource
    MenuService menuService;

    /** 菜单列表数据 */
    @GetMapping("/list")
    public Result<List<MenuListVo>> list() {
        List<MenuListVo> data = menuService.list();
        return Result.success(data);
    }

    /** 获取1级菜单列表 */
    @GetMapping("/list/1")
    public Result<List<MenuListVo>> list1() {
        List<MenuListVo> data = menuService.list1();
        return Result.success(data);
    }

    /** 菜单节点数据 */
    @GetMapping("/node")
    public Result<List<? extends NodeVo>> node(
            @RequestHeader("token") String token
    ) {
        Integer userId = JwtUtil.getUserId(token);
        List<MenuNodeVo> menuNodeVos = menuService.getMenuNodeByUser(userId);
        List<? extends NodeVo> data = NodeUtil.listWithTree(menuNodeVos);
        return Result.success(data);
    }

    /** 新增菜单 */
    @PostMapping("/add")
    public Result<String> addMenu(
            @RequestBody @Validated MenuAP param
    ) {
        SysMenu entity = new SysMenu();
        BeanUtil.copyPropIgnoreNull(param, entity);
        if (entity.getPid() == null) {
            entity.setPid(0);
        }
        menuService.addMenu(entity);
        return Result.success();
    }

    /** 删除菜单 */
    @DeleteMapping("/del")
    public Result<String> delMenu(
            @RequestParam  Integer menuId
    ) {
        boolean b = menuService.haveLowerLevel(menuId);
        if (b) {
            return Result.info(ResultEnum.ERROR, "有下级菜单，无法删除");
        }
        menuService.delMenu(menuId);
        return Result.success();
    }

    /** 修改菜单 */
    @PutMapping("/update")
    public Result<String> updateMenu(
            @Validated @RequestBody MenuUP param
    ) {
        SysMenu entity = new SysMenu();
        BeanUtil.copyPropIgnoreNull(param, entity);
        menuService.updateMenu(entity);
        return Result.success();
    }

}
